package com.atguigu.function;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.TableAggregateFunction;
import org.apache.flink.types.Row;
import org.apache.flink.util.Collector;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * 实现内容：自定义函数每传入一条数据可求出top2的数据
 */
public class UserDefinedFunction_TableAggreate {
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(1);

        DataStreamSource<WaterSensor> waterSensorStream =
                env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_2", 6000L, 60));
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        Table table = tEnv.fromDataStream(waterSensorStream);

        //1、注册表
        tEnv.createTemporaryView("sensor",table);


        //2、使用TableAPI调用
        Table resutl = table
                .groupBy($("id"))
                .flatAggregate(call(Top2.class, $("vc")))
                .select($("id"), $("rank"), $("value"));
        resutl
                .execute()
                .print();

        //将表转换为流
        DataStream<Tuple2<Boolean, Row>> ds = tEnv.toRetractStream(resutl, Row.class);

        ds.filter((FilterFunction<Tuple2<Boolean, Row>>) value -> value.f0)
                .print();
        env.execute();

    }

    //自定义函数
    public static class Top2 extends TableAggregateFunction<TwoData,MyAcc>{

        //初始化累加器
        @Override
        public MyAcc createAccumulator() {
            return new MyAcc();
        }

        //对数据进行累加
        public void accumulate(MyAcc acc,Integer value){
            if (value >acc.first){
                acc.second  = acc.first;
                acc.first = value;
            }else if (value > acc.second){
                acc.second = value;
            }
        }

        //定义结果输出
        public void emitValue(MyAcc acc, Collector<TwoData> out){

            //先判断是不是第一个进行的元素
            out.collect(new TwoData("第一", acc.first));
            if (acc.second > 0) {
                out.collect(new TwoData("第二", acc.second));
            }

        }

    }


    //定义输出结果类型
    public static class TwoData{
        public String rank;
        public Integer value;

        public TwoData(String rank, Integer value) {
            this.rank = rank;
            this.value = value;
        }
    }

    //定义累加器类型
    public static class MyAcc {
        public Integer first = 0;
        public Integer second = 0;

    }
}
